package log

import (
	"bufio"
	"io"
	"os"
	"syscall"
	"time"
)

type log struct {
	path    string
	writeCh chan []byte
	writer  io.Writer
}

func (l *log) open() error {
	file, err := os.OpenFile(l.path, syscall.O_CREAT|syscall.O_RDWR|syscall.O_APPEND, 0644)
	if err != nil {
		return err
	}
	l.writer = bufio.NewWriter(file)
	go l.handle()
	return nil
}

func (l *log) write(entry []byte) error {
	l.writeCh <- entry
	return nil
}

func (l *log) handle() {
	go func() {
		for {
			data := <-l.writeCh
			_, _ = l.writer.Write(data)
			time.Sleep(200)
		}
	}()
}

func (l *log) close() error {
	if bw, ok := l.writer.(*bufio.Writer); ok {
		return bw.Flush()
	}
	return nil
}
